package modele.database;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

public class OracleDB implements IDatabase {

	private Connection connection = null;
	
	private String url;
	private String username;
	private String password;
	
	public OracleDB(String url, String username, String password) {
		this.url = url;
		this.username = username;
		this.password = password;
	}

	@Override
	public void Connect() throws SQLException, ClassNotFoundException {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		connection = DriverManager.getConnection(url, username, password);
	}

	@Override
	public ArrayList<ArrayList<Object>> Select(String request, Object... param) throws SQLException {
		PreparedStatement preparedStatement = connection.prepareStatement(request);
		
		for(int i = 1; i != param.length + 1; ++i) {
			preparedStatement.setObject(i, param[i - 1]);
		}
 
		ResultSet rs = preparedStatement.executeQuery();
		ResultSetMetaData rsmd = rs.getMetaData();
 
		ArrayList<ArrayList<Object>> rows = new ArrayList<ArrayList<Object>>();
		while (rs.next()) {
			ArrayList<Object> columns = new ArrayList<Object>();
			
			for(int i = 0; i != rsmd.getColumnCount(); ++i) {
				columns.add(rs.getObject(rsmd.getColumnName(i + 1)));
			}
			
			rows.add(columns);
		}
		
		return rows;
	}
	
	private boolean ExecuteNonQuery(String request, Object... param) throws SQLException {
		PreparedStatement preparedStatement = connection.prepareStatement(request);
		
		for(int i = 1; i != param.length + 1; ++i) {
			preparedStatement.setObject(i, param[i - 1]);
		}
		
		int rowAffected = preparedStatement.executeUpdate();
		
		return rowAffected > 0;
	}

	@Override
	public boolean Insert(String request, Object... param) throws SQLException {
		return ExecuteNonQuery(request, param);
	}

	@Override
	public boolean Update(String request, Object... param) throws SQLException {
		return ExecuteNonQuery(request, param);
	}

	@Override
	public boolean Delete(String request, Object... param) throws SQLException {
		return ExecuteNonQuery(request, param);
	}

	@Override
	public void Close() throws SQLException {
		connection.close();	
	}
}
